﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace Trentacular.SharePoint.Features.Web.UI.WebParts
{
    public class ControlWrapperEditorPart<T> : BaseEditorPart<T> where T : WebPart
    {
        /// <summary>
        /// Virtual path to a UserControl that this EditorPart should wrap.
        /// The user control will be loaded when CreateChildControls is invoked, set
        /// on the EditorControl property, and added to the Controls collection.
        /// </summary>
        public string WrappedUserControlVirtualPath { get; private set; }

        public ControlWrapperEditorPart(string wrappedUserControlVirtualPath)
        {
            WrappedUserControlVirtualPath = wrappedUserControlVirtualPath;
        }

        public IWebPartEditor<T> EditorControl { get; private set; }

        protected override void CreateChildControls()
        {
            var control = Page.LoadControl(WrappedUserControlVirtualPath);
            EditorControl = control as IWebPartEditor<T>;

            if (EditorControl == null)
                throw new ArgumentException(
                    string.Format("The UserControl specified at path '{0}' does not implement '{1}'",
                        WrappedUserControlVirtualPath,
                        typeof(IWebPartEditor<T>).FullName)
                    );

            EditorControl.ParentWebPart = ParentWebPart;
            Controls.Add(control);
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            return EditorControl.ApplyChanges();
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            EditorControl.SyncChanges();
        }
    }
}
